<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { useAddMember, useGetLevelList, useGetSupplierLabel } from '@fl/api/man-api'
import FlUpload from '@fl/components/fl-upload.vue'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { ElLoading } from 'element-plus'
import { cloneDeep } from 'lodash-es'

const flUpload = ref()

const { data: levelData, isLoading: levelLoading } = useGetLevelList()

const { data: supplierData, isLoading: supplierLoading } = useGetSupplierLabel()

const { isPending, mutate } = useAddMember()

const loading = computed(() => levelLoading.value || supplierLoading.value)

const memberLevelIdOptions = computed(() => {
    return levelData.value
        ? levelData.value.map((item: any) => {
            return {
                fieldItemProps: {
                    disabled: item.status === 2,
                },
                label: item.levelName,
                value: item.levelId,
            }
        })
        : []
})

const enterpriseOptins = computed(() => {
    return supplierData.value
        ? supplierData.value.map((item: any) => {
            return {
                label: item.value,
                value: item.id,
            }
        })
        : []
})

const actTypeOptions = computed(() => {
    if (!id.value) {
        return [{
            label: '新增',
            value: 1,
        }]
    }
    return [
        {
            label: '续费',
            value: 2,
        },
        {
            label: '升级',
            value: 3,
        },
        {
            label: '续费升级',
            value: 4,
        },
    ]
})

const visible = defineModel<boolean>('visible', { required: true })

const id = defineModel<any>('id')

const form = defineModel<any>('form')

const title = computed(() => '会员信息')

const formRef = ref()

const oldMemberId = ref('')

const state = ref<any>(
    {
        actType: '',
        enterpriseId: '',
        expirationTime: '',
        memberLevelId: '',
        payTime: '',
        receipts: [],
        remark: '',
    },
)

const columns = computed<PlusColumn[]>(() => {
    return [
        {
            colProps: {
                span: 12,
            },
            fieldProps: computed(() => ({ disabled: Boolean(unref(id)), filterable: true })),
            label: '公司名称',
            options: enterpriseOptins.value,
            prop: 'enterpriseId',
            valueType: 'select',
        },
        {
            colProps: {
                span: 12,
            },
            fieldProps: {
                onChange: (val: any) => {
                    state.value.expirationTime = ''
                    if (val === 2 && id.value && oldMemberId.value) {
                        state.value.memberLevelId = oldMemberId.value
                    }
                },
            },
            label: '选择类型',
            options: actTypeOptions.value,
            prop: 'actType',
            valueType: 'select',
        },

        {
            colProps: {
                span: 24,
            },
            fieldProps: {
                type: 'date',
                valueFormat: 'YYYY-MM-DD',
            },
            hideInForm: computed(() => ![3, 4].includes(state.value.actType)),
            label: '有效期',
            prop: 'expirationTime',
            valueType: 'date-picker',
        },
        {
            colProps: {
                span: 12,
            },
            fieldProps: {
                type: 'date',
                valueFormat: 'YYYY-MM-DD',
            },
            label: '缴费日期',
            prop: 'payTime',
            valueType: 'date-picker',
        },
        {
            colProps: {
                span: 12,
            },
            fieldProps: computed(() => ({ disabled: state.value.actType === 2 })),
            label: '会员等级',
            options: memberLevelIdOptions.value,
            prop: 'memberLevelId',
            valueType: 'select',
        },
        {
            colProps: {
                span: 24,
            },
            fieldProps: {
                maxlength: 500,
            },
            label: '备注',
            prop: 'remark',
            valueType: 'textarea',
        },
        {
            colProps: {
                span: 24,
            },
            label: '附件',
            prop: 'receipts',
        },
    ]
})

const rules = {
    actType: [
        {
            message: '请选择类型',
            required: true,
        },
    ],
    enterpriseId: [
        {
            message: '请选择公司名称',
            required: true,
        },
    ],
    expirationTime: [
        {
            message: '请选择有效期',
            required: true,
        },
    ],
    memberLevelId: [
        {
            message: '请选择会员等级',
            required: true,
        },
    ],
    payTime: [
        {
            message: '请选择缴费日期',
            required: true,
        },
    ],
    receipts: [
        {
            message: '请上传附件',
            required: true,
        },
    ],
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
    form.value = ''
    oldMemberId.value = ''
}

async function save() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const { memberLevelName, ...rest } = unref(state)
        const params = {
            ...rest,
            enterpriseName: enterpriseOptins.value.filter((item: any) => item.value === state.value.enterpriseId)[0]?.label,
            memberId: id.value,
            receipts: state.value.receipts,
        }

        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function servicesLoading(node, str, lock, bg) {
    return ElLoading.service({
 	background: bg, // 背景色与透明度
        lock, // 同v-loading的修饰符
        // loading需要覆盖的DOM节点，默认为body
        target: document.querySelector(node),
        text: str, // 加载文案
    // spinner: 'el-icon-loading',	 //加载图标
    })
}

const uploadFileStatus = ref(false)
const loadingInstance = ref<any>(null)
function uploadFileStart() {
    uploadFileStatus.value = true
    loadingInstance.value = servicesLoading('.el-dialog.upload-file-dialog', '正在上传中,请耐心等待', true, 'rgba(0,0,0,0.3)')
}
function uploadSuccess(data: any) {
    if (data.url) {
        uploadFileStatus.value = false
        setTimeout(() => {
            loadingInstance.value.close()
            ElMessage.success('图片上传成功')
        }, 1000)
    }
}

watchEffect(() => {
    if (form.value) {
        state.value = Object.assign(state.value, form.value)
        oldMemberId.value = form.value.memberLevelId
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                @cancel="cancel"
                @closed="reset"
    >
        <el-skeleton v-if="loading"
                     :rows="5"
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :row-props="{ gutter: 20 }"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-receipts>
                <FlUpload ref="flUpload"
                          v-model="state.receipts"
                          is-mall-admin
                          list-type="text"
                          :limit="5"
                          :file-size="50"
                          accept="*"
                          @start="uploadFileStart"
                          @success="uploadSuccess"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="save"
                >
                    保存
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
